package com.hmdp.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
public class RedisIdWorker {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final Long BEGIN_TIME = 1735689600L;

    private static final Long COUNT_BITS = 32L;

    public Long nextId(String keyPreFix) {
        //生成时间戳
        LocalDateTime now = LocalDateTime.now();
        Long nowEpochSecond = now.toEpochSecond(ZoneOffset.UTC);
        Long timestamp = nowEpochSecond - BEGIN_TIME;

        //生成序列号
        //获取到当前日期，精确到天
        String data = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        //自增
        Long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPreFix + ":" + data);
        //使用位运算拼接返回
        return timestamp << COUNT_BITS | count;
    }
}
